<!-- 用户菜单管理增改弹窗 -->

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin: 15px 0;
  }

  .hjd-drawer__footer {
    margin-top: 50px;
  }
}
::v-deep {
  .el-select {
    width: 100%;
    .el-input {
      width: 100%;
    }
  }
}
</style>

<template>
  <el-drawer
    ref="drawer"
    custom-class="hjd-drawer"
    :title="`${status === 'create' ? '新增' :(status === 'childCreate' ?'新增子':'编辑') }菜单`"
    :visible.sync="showDialog"
    :wrapper-closable="true"
    @close="$emit('update', false)"
  >
    <div class="hjd-drawer__content">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-width="100px"
        style=" margin-left:20px;margin-right:20px;"
      >
        <div class="hjd-drawer__content_tree">

          <el-form-item label="父级菜单">
            <el-cascader
              v-if="cascaderVisible"
              v-model="parendIds"
              :props="props"
              style="width: 100%;"
            >
              <template slot-scope="scope">
                <span :style="{ color: scope.data.color ? scope.data.color : '' }">
                  {{ scope.node.label }}
                </span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item label="菜单名称" prop="menu_name">
            <el-input v-model="form.menu_name" />
          </el-form-item>

          <el-form-item label="图标" prop="icon_name">
            <el-input v-model="form.icon_name" />
          </el-form-item>

          <el-form-item label="路径" prop="route_path">
            <el-input v-model="form.route_path" />
          </el-form-item>

          <el-form-item label="默认跳转" prop="redirect">
            <el-input v-model="form.redirect" />
          </el-form-item>

          <el-form-item label="接口地址" prop="route_api">
            <el-input v-model="form.route_api" />
          </el-form-item>

          <el-form-item label="菜单类型" prop="menu_type">
            <el-select
              v-model="form.menu_type"
              placeholder="请选择"
            >
              <el-option
                label="目录"
                value="1"
              />
              <el-option
                label="菜单"
                value="2"
              />
              <el-option
                label="按钮"
                value="3"
              />
              <el-option
                label="其他"
                value="4"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="排序">
            <el-input v-model="form.sort" type="number" />
          </el-form-item>

          <el-form-item label="是否启用" prop="status">
            <el-switch v-model="form.status" />
          </el-form-item>

          <el-form-item label="固定标签">
            <el-switch v-model="form.affix" />
          </el-form-item>

          <el-form-item label="隐藏">
            <el-switch v-model="form.hidden" />
          </el-form-item>
        </div>
        <div class="hjd-drawer__footer">
          <el-button @click="showDialog = false">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="submit"
          >
            确定
          </el-button>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>

import _ from 'lodash'

import { menuList, createMenu, editMenu } from '@/api/member/menu'

export default {
  name: 'UpdateMenuDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'new'
    },
    data: {
      type: Object,
      default: () => ({})
    },

    parent: {
      type: Array,
      default: () => []
    },

    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showDialog: this.visible,

      beforeData: {},

      cascaderVisible: false,

      /**
       * 表单内容
       */
      form: {
        // 父级id
        menu_pid: '0',
        // 菜单名称
        menu_name: '',
        // icon
        icon_name: '',
        // 默认跳转
        redirect: '',
        // 前端路由路径
        route_path: '/',
        // 接口地址
        route_api: '/',
        // 启动状态
        status: 1,
        // 菜单类型
        menu_type: '',
        // 排序
        sort: 0,
        // 是否固定标签
        affix: 0,
        // 是否隐藏
        hidden: 0
      },

      rules: {
        menu_name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        route_url: [
          { required: true, message: '请输入前端路由', trigger: 'blur' }
        ],
        route_api: [
          { required: true, message: '请输入接口地址', trigger: 'blur' }
        ],
        menu_type: [
          { required: true, message: '请选择菜单类型', trigger: 'change' }
        ]

      },

      parendIds: [],

      props: {
        checkStrictly: true,
        label: 'menu_name',
        value: 'menu_id',
        lazy: true,
        lazyLoad: (node, resolve) => {
          let id = ''
          if (node.root) {
            id = 0
          } else {
            id = node.data.menu_id
          }

          // 没有子级
          if (!_.get(node, 'data.hasChildren', true)) {
            resolve([])
            return
          }

          menuList({
            menu_pid: id,
            page: 1,
            limit: 10000
          }).then(res => {
            const list = res.data.data

            _.forEach(list, item => {
              item.leaf = !item.hasChildren

              if (this.status === 'update' && item.menu_id === this.data.menu_id) {
                item.disabled = true
                item.leaf = true
                item.hasChildren = false
                item.color = '#ccc'
              }
            })

            if (node.root) {
            // 第一次获取 先在最上面加一个顶级
              list.unshift({
                menu_id: -1,
                menu_name: '顶级',
                leaf: true,
                hasChildren: false
              })
            }

            resolve(list)
          })
        }
      }
    }
  },

  watch: {
    visible(val) {
      this.showDialog = this.visible

      if (val) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })

        const ids = _.cloneDeep(_.get(this.data, 'parent.menu_id', []))

        this.data.menu_type = `${this.data.menu_type}`

        // 编辑
        if (this.status === 'update') {
          this.form.menu_id = ''
          _.keys(this.form).forEach((key) => {
            this.form[key] = this.data[key]
          })
          this.form.menu_pid = ''
          this.beforeData = _.cloneDeep(this.form)

          this.parendIds = _.initial(ids)
        } else {
          this.parendIds = ids
        }

        if (this.parendIds.length === 0) this.parendIds = [-1]

        if (this.status === 'childCreate') {
          this.form.menu_pid = this.data.menu_id
        }

        this.resetCascader()
      } else {
        // 关闭逻辑

        this.parendIds = []

        this.form = {
        // 父级id
          menu_pid: '0',
          // 菜单名称
          menu_name: '',
          // icon
          icon_name: '',
          // 默认跳转
          redirect: '',
          // 前端路由路径
          route_path: '/',
          // 接口地址
          route_api: '/',
          // 启动状态
          status: 1,
          // 菜单类型
          menu_type: '',
          // 排序
          sort: 0,
          // 是否固定标签
          affix: 0,
          // 是否隐藏
          hidden: 0
        }
      }
    },

    list() {
      // 构造列表
      // this.options = _.concat([{
      //   menu_id: '0',
      //   menu_name: '顶级'
      // }], _.cloneDeep(this.list))
    }
  },

  methods: {
    submit() {
      const pid = _.get(this.parendIds, this.parendIds.length - 1, 0)
      this.form.menu_pid = pid !== -1 ? pid : 0

      // 数据没改动 直接关闭弹窗
      if (_.isEqual(this.form, this.beforeData)) {
        this.showDialog = false
        return
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 是否是创建
          const isCreate = this.status === 'create' || this.status === 'childCreate'

          // 请求数据
          const queryData = _.cloneDeep(this.form)

          // 修改时传 ID
          if (!isCreate) queryData['menu_id'] = this.form.menu_id

          // 请求接口
          const request = isCreate ? createMenu : editMenu
          request(queryData).then(() => {
            this.showDialog = false
            this.$message.success(isCreate ? '创建成功' : '修改成功')
            this.$emit('reload', true) // 刷新列表
          })
        }
      })
    },

    resetCascader() {
      this.cascaderVisible = false
      this.$nextTick(() => {
        this.cascaderVisible = true
      })
    }
  }
}
</script>
